<template>
	<view class="problem-page" :class="{ 'dark-mode': isDarkMode }">
		<NavBar @theme-change="onThemeChange"></NavBar>

		<view class="content">
			<view class="problem-section">
				<view class="filter-box">
					<view class="search-box">
						<input type="text" v-model="searchKeyword" placeholder="搜索题目..." />
						<button @click="searchProblems">搜索</button>
					</view>
					<view class="difficulty-filter">
						<text v-for="(diff, index) in difficulties" :key="index"
							:class="['diff-tag', { active: selectedDifficulties.includes(diff.value) }]"
							:style="{ color: selectedDifficulties.includes(diff.value) ? diff.color : '#666' }"
							@click="toggleDifficulty(diff.value)">
							{{ diff.label }}
						</text>
					</view>
					<view class="filter-section">
						<view class="filter-title">算法标签：</view>
						<view class="tags-filter">
							<text v-for="(tag, index) in algorithmTags" :key="index"
								:class="['tag-item', { active: selectedTags.includes(tag) }]" @click="toggleTag(tag)">
								{{ tag }}
							</text>
						</view>
					</view>
					<view class="filter-section">
						<view class="filter-title">题目来源：</view>
						<view class="source-filter">
							<text v-for="(source, index) in examSources" :key="index"
								:class="['source-item', { active: selectedSources.includes(source) }]"
								@click="toggleSource(source)">
								{{ source }}
							</text>
						</view>
					</view>
				</view>

				<view class="problem-table">
					<view class="table-header">
						<view class="col col-status">状态</view>
						<view class="col col-id" @click="sortBy('id')">
							编号
							<text v-if="sortField === 'id'"
								class="sort-icon">{{ sortOrder === 'asc' ? '↑' : '↓' }}</text>
						</view>
						<view class="col col-title">题目</view>
						<view class="col col-tags">算法标签</view>
						<view class="col col-source">来源</view>
						<view class="col col-difficulty" @click="sortBy('difficulty')">
							难度
							<text v-if="sortField === 'difficulty'"
								class="sort-icon">{{ sortOrder === 'asc' ? '↑' : '↓' }}</text>
						</view>
						<view class="col col-pass-rate" @click="sortBy('passRate')">
							通过率
							<text v-if="sortField === 'passRate'"
								class="sort-icon">{{ sortOrder === 'asc' ? '↑' : '↓' }}</text>
						</view>
					</view>

					<view v-for="(problem, index) in filteredProblems" :key="index" class="table-row"
						:class="{ 'dark-row': isDarkMode }" @click="navigateToProblem(problem.id)">
						<view class="col col-status">
							<view class="status-wrapper">
								<text v-if="problem.status !== 'unsolved'" class="status-text" :class="problem.status">
									{{ problem.status }}
								</text>
								<text v-else class="status-circle"></text>
								<text v-if="problem.status === 'WA'" class="problem-score">
									{{ problem.score || 0 }}分
								</text>
							</view>
						</view>
						<view class="col col-id">{{ problem.problem_no || problem.id }}</view>
						<view class="col col-title">{{ problem.title }}</view>
						<view class="col col-tags">
							<text v-for="(tag, tagIndex) in problem.tags" :key="tagIndex" class="problem-tag"
								:class="{ 'dark-problem-tag': isDarkMode }">
								{{ tag }}
							</text>
						</view>
						<view class="col col-source">{{ problem.source }}</view>
						<view class="col col-difficulty" :style="{ color: getDifficultyColor(problem.difficulty) }">
							{{ problem.difficulty }}
						</view>
						<view class="col col-pass-rate">{{ problem.passRate }}</view>
					</view>

					<view v-if="filteredProblems.length === 0" class="empty-tip">
						没有找到符合条件的题目
					</view>
				</view>

				<view class="pagination">
					<text @click="changePage(currentPage - 1)" :class="{ disabled: currentPage <= 1 }">上一页</text>
					<text v-for="page in displayedPages" :key="page" :class="{ active: currentPage === page }"
						@click="changePage(page)">
						{{ page }}
					</text>
					<text @click="changePage(currentPage + 1)"
						:class="{ disabled: currentPage >= totalPages }">下一页</text>
				</view>
			</view>

			<view class="calendar-section">
				<ContestCalendar />
			</view>
		</view>
	</view>
</template>

<script>
	import NavBar from '@/components/NavBar.vue';
	import ContestCalendar from '@/components/ContestCalendar.vue';
	import {
		getThemeMode
	} from '@/utils/themeManager.js';

	export default {
		components: {
			NavBar,
			ContestCalendar
		},
		data() {
			return {
				isDarkMode: false,
				problems: [{
					id: 123,
					title: "两数之和",
					difficulty: 1,
					tags: ["数组", "哈希表"]
				}],
				searchKeyword: '',
				selectedDifficulties: [],
				currentPage: 1,
				pageSize: 10,
				totalProblems: 0,
				difficulties: [{
						label: '入门',
						value: '入门',
						color: '#00b800'
					},
					{
						label: '简单',
						value: '简单',
						color: '#3498db'
					},
					{
						label: '中等',
						value: '中等',
						color: '#f39c12'
					},
					{
						label: '困难',
						value: '困难',
						color: '#e74c3c'
					},
					{
						label: '专家',
						value: '专家',
						color: '#9b59b6'
					}
				],
				selectedTags: [],
				selectedSources: [],
				algorithmTags: [
					'动态规划', '贪心算法', '回溯算法', '分治算法', '图论',
					'树', '哈希表', '堆', '栈', '队列', '字符串', '排序', '搜索'
				],
				examSources: [
					'NOI', 'NOIP', 'CSP', '蓝桥杯', 'ICPC', '校内练习', '自创题目'
				],
				statusMap: {
					'PENDING': '等待测评',
					'PENDING_REJUDGE': '等待重测',
					'COMPILING': '正在编译',
					'JUDGING': '正在测评',
					'AC': '通过',
					'PE': '格式错误',
					'WA': '解答错误',
					'TLE': '运行超时',
					'MLE': '内存超限',
					'OLE': '输出超限',
					'RE': '运行出错',
					'CE': '编译错误',
					'unsolved': '未解答',
					'attempted': '尝试过'
				},
				sortField: 'id',
				sortOrder: 'asc'
			};
		},
		computed: {
			filteredProblems() {
				return this.problems;
			},
			totalPages() {
				return Math.ceil(this.totalProblems / this.pageSize);
			},
			displayedPages() {
				const pages = [];
				const totalPagesToShow = 5;

				let startPage = Math.max(1, this.currentPage - Math.floor(totalPagesToShow / 2));
				const endPage = Math.min(startPage + totalPagesToShow - 1, this.totalPages);

				if (endPage - startPage + 1 < totalPagesToShow) {
					startPage = Math.max(1, endPage - totalPagesToShow + 1);
				}

				for (let i = startPage; i <= endPage; i++) {
					pages.push(i);
				}

				return pages;
			}
		},
		onLoad() {
			// 检查当前主题
			this.isDarkMode = getThemeMode();

			// 监听全局主题变更
			uni.$on('global-theme-changed', (isDark) => {
				this.isDarkMode = isDark;
			});

			// 加载题目数据
			this.loadProblems();
		},
		onUnload() {
			uni.$off('global-theme-changed');
		},
		methods: {
			// 加载题目数据
			loadProblems() {
				// 构建参数
				const params = {
					page: this.currentPage,
					size: this.pageSize
				};
				
				// 添加排序参数
				if (this.sortField) {
					params.sort_field = this.sortField;
					params.sort_order = this.sortOrder;
				}
				
				// 添加过滤参数
				if (this.searchKeyword) {
					params.keyword = this.searchKeyword;
				}
				
				if (this.selectedDifficulties.length > 0) {
					params.difficulties = this.selectedDifficulties.join(',');
				}
				
				if (this.selectedTags.length > 0) {
					params.tags = this.selectedTags.join(',');
				}
				
				if (this.selectedSources.length > 0) {
					params.sources = this.selectedSources.join(',');
				}
				
				// 获取用户ID（如果有的话）
				const userId = uni.getStorageSync('userId');
				if (userId) {
					params.user_id = userId;
				}
				
				// 显示加载提示
				uni.showLoading({
					title: '加载中...'
				});
				
				// 调用API
				// uni.request({
				// 	url: 'http://59.110.32.186:5000/problems',
				// 	method: 'GET',
				// 	data: params,
				// 	success: (res) => {
				// 		console.log('API响应:', res);
				// 		if (res.statusCode === 200 && res.data) {
				// 			// 确保problems是数组
				// 			if (Array.isArray(res.data.problems)) {
				// 				this.problems = res.data.problems;
				// 			} else {
				// 				console.error('返回的problems不是数组:', res.data.problems);
				// 				this.problems = []; // 设置为空数组
				// 			}
							
				// 			this.totalProblems = res.data.total || 0;
				// 			this.currentPage = res.data.page || 1;
				// 			this.pageSize = res.data.size || 10;
				// 		} else {
				// 			// 错误处理
				// 			uni.showToast({
				// 				title: '加载题目失败',
				// 				icon: 'none'
				// 			});
				// 			console.error('加载题目失败:', res);
				// 			this.problems = []; // 确保设置为空数组
				// 		}
				// 	},
				// 	fail: (err) => {
				// 		// 错误处理
				// 		uni.showToast({
				// 			title: '网络请求失败',
				// 			icon: 'none'
				// 		});
				// 		console.error('网络请求失败:', err);
				// 		this.problems = []; // 确保设置为空数组
				// 	},
				// 	complete: () => {
				// 		// 隐藏加载提示
				// 		uni.hideLoading();
				// 	}
				// });
				uni.hideLoading()
			},
			searchProblems() {
				this.currentPage = 1;
				this.loadProblems();
			},
			toggleDifficulty(difficulty) {
				const index = this.selectedDifficulties.indexOf(difficulty);
				if (index === -1) {
					this.selectedDifficulties.push(difficulty);
				} else {
					this.selectedDifficulties.splice(index, 1);
				}
				this.currentPage = 1;
				this.loadProblems();
			},
			getDifficultyColor(difficulty) {
				const diff = this.difficulties.find(d => d.value === difficulty);
				return diff ? diff.color : '#666';
			},
			changePage(page) {
				if (page >= 1 && page <= this.totalPages) {
					this.currentPage = page;
					this.loadProblems();
				}
			},
			navigateToProblem(id) {
				uni.navigateTo({
					url: `/pages/problem/detail?id=${id}`
				});
			},
			toggleTag(tag) {
				const index = this.selectedTags.indexOf(tag);
				if (index === -1) {
					this.selectedTags.push(tag);
				} else {
					this.selectedTags.splice(index, 1);
				}
				this.currentPage = 1;
				this.loadProblems();
			},
			toggleSource(source) {
				const index = this.selectedSources.indexOf(source);
				if (index === -1) {
					this.selectedSources.push(source);
				} else {
					this.selectedSources.splice(index, 1);
				}
				this.currentPage = 1;
				this.loadProblems();
			},
			sortBy(field) {
				if (this.sortField === field) {
					this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
				} else {
					this.sortField = field;
					this.sortOrder = 'asc';
				}
				this.loadProblems();
			},
			onThemeChange(isDark) {
				this.isDarkMode = isDark;
			}
		}
	};
</script>

<style>
	/* 整体容器和内容区 */
	.problem-page {
		width: 100%;
		min-height: 100vh;
		background-color: #f8f9fa;
		padding-top: 60px;
		box-sizing: border-box;
	}

	.problem-page.dark-mode {
		background-color: #121212;
		color: #e0e0e0;
	}

	.content {
		padding: 20px;
		display: flex;
		max-width: 1440px;
		margin: 0 auto;
	}

	.dark-mode .content {
		background-color: #121212;
	}

	/* 左侧问题区域 */
	.problem-section {
		flex: 1;
		margin-right: 20px;
		background-color: transparent;
	}

	/* 过滤器盒子 */
	.filter-box {
		background-color: white;
		border-radius: 8px;
		padding: 15px;
		margin-bottom: 20px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
	}

	.dark-mode .filter-box {
		background-color: #1e1e1e;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
		border: 1px solid #333;
	}

	/* 搜索框优化 */
	.search-box {
		display: flex;
		margin-bottom: 15px;
		border-radius: 4px;
		overflow: hidden;
		box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
	}

	.search-box input {
		flex: 1;
		padding: 12px 15px;
		border: 1px solid #ddd;
		border-right: none;
		border-radius: 4px 0 0 4px;
		outline: none;
		font-size: 15px;
		height: 46px;
		box-sizing: border-box;
	}

	.dark-mode .search-box input {
		background-color: #2a2a2a;
		border-color: #444;
		color: #e0e0e0;
		box-shadow: none;
	}

	.dark-mode .search-box input::placeholder {
		color: #888;
	}

	.search-box button {
		width: 80px;
		background-color: #20C0B8;
		color: white;
		border: none;
		font-size: 15px;
		cursor: pointer;
		height: 46px;
		border-radius: 0 4px 4px 0;
		transition: background-color 0.2s;
	}

	.search-box button:hover {
		background-color: #1aa8a1;
	}

	.dark-mode .search-box button {
		background-color: #158782;
		color: #ffffff;
	}

	.dark-mode .search-box button:hover {
		background-color: #106e69;
	}

	/* 难度过滤器 */
	.difficulty-filter {
		display: flex;
		margin-bottom: 15px;
		flex-wrap: wrap;
	}

	.diff-tag {
		padding: 5px 15px;
		margin-right: 10px;
		margin-bottom: 10px;
		border-radius: 20px;
		background-color: #f5f5f5;
		cursor: pointer;
		transition: all 0.2s;
		border: 1px solid transparent;
	}

	.diff-tag.active {
		background: rgba(32, 192, 184, 0.1);
	}

	.dark-mode .diff-tag {
		background-color: #2a2a2a;
		border-color: #444;
		color: #aaa !important;
	}

	.dark-mode .diff-tag.active {
		background-color: rgba(32, 192, 184, 0.2);
		color: #20C0B8 !important;
	}

	/* 题目表格 */
	.problem-table {
		background-color: white;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
	}

	.dark-mode .problem-table {
		background-color: #1e1e1e;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
		border: 1px solid #333;
	}

	.table-header {
		display: flex;
		background-color: #f5f5f5;
		padding: 12px 10px;
		font-weight: 500;
		border-bottom: 1px solid #eee;
		color: #333;
	}

	.dark-mode .table-header {
		background-color: #252525;
		color: #e0e0e0;
		border-bottom-color: #444;
	}

	.table-row {
		display: flex;
		padding: 12px 10px;
		border-bottom: 1px solid #eee;
		cursor: pointer;
		transition: background-color 0.1s;
	}

	.dark-mode .table-row {
		border-bottom-color: #333;
	}

	.table-row:hover {
		background-color: #f9f9f9;
	}

	.dark-mode .table-row:hover {
		background-color: #2a2a2a;
	}

	.col {
		padding: 0 5px;
	}

	.dark-mode .col {
		color: #e0e0e0;
	}

	/* 列宽度和样式 */
	.col-status {
		width: 60px;
		text-align: center;
	}

	.col-id {
		width: 100px;
	}

	.col-title {
		flex: 1;
	}

	.col-tags {
		width: 200px;
		display: flex;
		flex-wrap: wrap;
	}

	.col-source {
		width: 100px;
	}

	.col-difficulty {
		width: 80px;
	}

	.col-pass-rate {
		width: 80px;
	}

	/* 状态样式 */
	.status-wrapper {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.status-text {
		font-size: 14px;
		font-weight: bold;
	}

	.status-circle {
		width: 12px;
		height: 12px;
		border-radius: 50%;
		background-color: #ddd;
		display: inline-block;
	}

	.dark-mode .status-circle {
		background-color: #555;
	}

	.status-text.AC {
		color: #00b800;
	}

	.status-text.WA {
		color: #e74c3c;
	}

	.status-text.TLE,
	.status-text.MLE,
	.status-text.OLE {
		color: #f39c12;
	}

	.status-text.RE,
	.status-text.CE {
		color: #9b59b6;
	}

	.status-text.PENDING,
	.status-text.PENDING_REJUDGE,
	.status-text.COMPILING,
	.status-text.JUDGING {
		color: #3498db;
	}

	.problem-score {
		font-size: 12px;
		color: #666;
		margin-top: 3px;
	}

	.dark-mode .problem-score {
		color: #aaa;
	}

	/* 右侧日历区域 */
	.calendar-section {
		width: 300px;
		background-color: white;
		border-radius: 8px;
		padding: 15px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
	}

	.dark-mode .calendar-section {
		background-color: #1e1e1e;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
		border: 1px solid #333;
	}

	/* 标签样式调整 */
	.algorithm-tags,
	.source-tags {
		margin-top: 15px;
	}

	.tag-title {
		font-size: 14px;
		color: #666;
		margin-bottom: 10px;
		display: block;
	}

	.dark-mode .tag-title {
		color: #aaa;
	}

	.tag-item,
	.source-item {
		padding: 5px 10px;
		margin-right: 8px;
		margin-bottom: 8px;
		border-radius: 16px;
		background: #f5f5f5;
		cursor: pointer;
		font-size: 14px;
		color: #666;
		display: inline-block;
	}

	.dark-mode .tag-item,
	.dark-mode .source-item {
		background-color: #2a2a2a;
		color: #aaa;
		border: 1px solid #444;
	}

	.tag-item.active,
	.source-item.active {
		background: rgba(32, 192, 184, 0.1);
		color: #20C0B8;
		border-color: #20C0B8;
	}

	.dark-mode .tag-item.active,
	.dark-mode .source-item.active {
		background-color: rgba(32, 192, 184, 0.2);
		color: #20C0B8;
		border-color: #20C0B8;
	}

	/* 题目标签 */
	.problem-tag {
		font-size: 12px;
		padding: 2px 6px;
		margin-right: 4px;
		margin-bottom: 4px;
		background-color: rgba(32, 192, 184, 0.1);
		color: #20C0B8;
		border-radius: 4px;
		white-space: nowrap;
	}

	.dark-mode .problem-tag {
		background-color: rgba(32, 192, 184, 0.15);
		color: #20C0B8;
	}

	/* 排序图标 */
	.sort-icon {
		margin-left: 5px;
		font-size: 12px;
	}

	.dark-mode .sort-icon {
		color: #20C0B8;
	}

	/* 空状态提示 */
	.empty-tip {
		padding: 30px;
		text-align: center;
		color: #666;
	}

	.dark-mode .empty-tip {
		color: #aaa;
	}

	/* 分页 */
	.pagination {
		display: flex;
		justify-content: center;
		padding: 20px 0;
	}

	.pagination text {
		margin: 0 5px;
		padding: 5px 10px;
		cursor: pointer;
		border-radius: 4px;
		color: #333;
	}

	.pagination text:hover:not(.active):not(.disabled) {
		background-color: #f0f0f0;
	}

	.pagination text.active {
		background-color: #20C0B8;
		color: white;
	}

	.pagination text.disabled {
		color: #ccc;
		cursor: not-allowed;
	}

	.dark-mode .pagination text {
		color: #e0e0e0;
	}

	.dark-mode .pagination text:hover:not(.active):not(.disabled) {
		background-color: #2a2a2a;
	}

	.dark-mode .pagination text.active {
		background-color: #158782;
	}

	.dark-mode .pagination text.disabled {
		color: #555;
	}

	/* 日历部分暗黑模式完善 */
	.dark-mode .calendar-header {
		color: #e0e0e0;
		border-bottom-color: #444;
	}

	.dark-mode .calendar-title {
		color: #e0e0e0;
	}

	.dark-mode .calendar-days {
		color: #aaa;
	}

	.dark-mode .calendar-grid {
		border-color: #444;
	}

	.dark-mode .calendar-day {
		background-color: #2a2a2a;
		border-color: #444;
		color: #aaa;
	}

	.dark-mode .calendar-day.current-day {
		background-color: rgba(32, 192, 184, 0.15);
		color: #20C0B8;
		border-color: #20C0B8;
	}

	.dark-mode .calendar-day.has-submission {
		background-color: rgba(32, 192, 184, 0.1);
	}

	.dark-mode .calendar-day.has-submission:hover {
		background-color: rgba(32, 192, 184, 0.2);
	}

	.dark-mode .calendar-day.other-month {
		color: #555;
		background-color: #222;
	}

	.dark-mode .weekday-header {
		color: #888;
		border-bottom-color: #444;
	}

	.dark-mode .month-selector {
		background-color: #1e1e1e;
		border-color: #444;
		color: #e0e0e0;
	}

	.dark-mode .month-arrow {
		color: #aaa;
	}

	.dark-mode .month-arrow:hover {
		color: #20C0B8;
		background-color: #2a2a2a;
	}

	/* 每日一题部分 */
	.dark-mode .daily-challenge {
		background-color: #1e1e1e;
		border-color: #444;
	}

	.dark-mode .daily-challenge-title {
		color: #e0e0e0;
		border-bottom-color: #444;
	}

	.dark-mode .daily-challenge-date {
		color: #aaa;
	}

	.dark-mode .daily-problem {
		border-color: #444;
	}

	.dark-mode .daily-problem-title {
		color: #e0e0e0;
	}

	.dark-mode .daily-problem-difficulty {
		color: inherit;
	}

	.dark-mode .daily-problem-tags span {
		background-color: #2a2a2a;
		color: #aaa;
		border-color: #444;
	}

	/* 距离比赛部分 */
	.dark-mode .upcoming-contest {
		background-color: #1e1e1e;
		border-top-color: #444;
	}

	.dark-mode .upcoming-contest-title {
		color: #e0e0e0;
	}

	.dark-mode .contest-item {
		border-bottom-color: #444;
	}

	.dark-mode .contest-name {
		color: #e0e0e0;
	}

	.dark-mode .contest-date {
		color: #aaa;
	}

	.dark-mode .contest-countdown {
		color: #ff7675;
	}

	/* 标题和文本通用样式 */
	.dark-mode .section-title {
		color: #e0e0e0;
	}

	.dark-mode .section-subtitle {
		color: #aaa;
	}

	/* 如果有其他特定的日历组件样式也需要添加 */
	.dark-mode .day-checkbox {
		background-color: #2a2a2a;
		border-color: #444;
	}

	.dark-mode .day-checkbox.checked {
		background-color: #158782;
		border-color: #158782;
	}

	.dark-mode .day-label {
		color: #aaa;
	}

	.dark-mode .day-has-event {
		color: #20C0B8;
	}

	/* 如果使用的是表格样式的日历，补充这些样式 */
	.dark-mode table.calendar-table {
		border-color: #444;
	}

	.dark-mode .calendar-table th {
		background-color: #252525;
		color: #aaa;
		border-color: #444;
	}

	.dark-mode .calendar-table td {
		border-color: #444;
		color: #e0e0e0;
	}

	.dark-mode .calendar-table td.today {
		background-color: rgba(32, 192, 184, 0.15);
		color: #20C0B8;
	}

	.dark-mode .calendar-table td.different-month {
		color: #555;
	}

	.dark-mode .calendar-table td.has-event {
		background-color: rgba(32, 192, 184, 0.1);
	}

	/* 如果有日历中的徽章或指示器 */
	.dark-mode .day-badge {
		background-color: #158782;
		color: white;
	}

	.dark-mode .day-indicator {
		background-color: #20C0B8;
	}

	.dark-mode .day-dot {
		background-color: #20C0B8;
	}
</style>